<?php

class openapi_api_function_v1_member extends openapi_api_function_abstract implements openapi_api_function_interface{

    public function modpwd($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $obj_member = app::get('b2c')->model('members');
        $result = $obj_member->save_security($member_id,$params,$msg);
        if($result){
            return $this->apiData(true,array('member_id'=>$member_id),200,app::get('b2c')->_('修改成功'));
        }else{
            return $this->apiData(false,array('member_id'=>$member_id),400,$msg);
        }
    }

    
    public function modPayPwd($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $members = app::get('b2c')->model('members');
        $pay_password = $members->getRow('pay_password',array('member_id'=>$member_id));
        //固定不填旧密码
        $params['old_passwd'] = $pay_password['pay_password'];
        //默认固定为修改
        $params['isSet'] = '1';
        $result = array();
        $result['noSet'] = false;
        if(!$pay_password['pay_password']){
            $result['noSet'] = true;
        }
        if($params['isSet'] == '1')//如果是提交
        {
            $myoutpassword = $pay_password['pay_password'];//得到我的支付密码
            $advance_password = md5($params['passwd']);
            $oldmy_password = $params['old_passwd'];
            
            if(!$result['noSet'] && $oldmy_password && ($oldmy_password != $myoutpassword)){
                return $this->apiData(false,null,400,app::get('b2c')->_('密码验证失败'));
            }elseif($advance_password == $myoutpassword){
                return $this->apiData(false,null,400,app::get('b2c')->_('新密码和旧密码相同'));
            }else{
                $data = array(
                    'member_id'=>$member_id,
                    'pay_password'=>$advance_password,
                  );
                $rs = $members->save($data);
                if($rs){
                    return $this->apiData(true,null,200,app::get('b2c')->_('设置成功'));
                }else{
                    return $this->apiData(false,null,400,app::get('b2c')->_('设置失败'));
                }
            }
        }
        
        return $this->apiData(true,$result,200);
    }

    public function userinfo($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $membermdl = app::get('b2c')->model('members');
        $member = $membermdl->getList("sex,mobile,email,seller",array('member_id'=>$member_id));
        $member = $member[0];
        $login_name = app::get('pam') -> model('account') -> get_operactor_name($member_id);
        $member['login_name'] = $login_name;
        $store = app::get('business')->model('storemanger')->getList("store_id,store_idcardname",array('account_id'=>$member_id));
        $member['real_name'] = $store[0]['store_idcardname'];
        $member['store_id'] = $store[0]['store_id'];
        return $this->apiData(true,$member,200);
    }

    public function editinfo($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $db = kernel::database();
        $membermdl = app::get('b2c')->model('members');
        $member['member_id'] = $member_id;
        $member['profile']['gender'] = "{$params['gender']}";
        $member['contact']['phone']['mobile'] = $params['mobile'];
        $member['contact']['email'] = $params['email'];
        $member['contact']['area'] = $params['area'];
        $member['contact']['addr'] = $params['addr'];
        if($member['contact']['email']&&$membermdl->is_exists_email($member['contact']['email'],$member['member_id'])){
            return $this->apiData(false,null,400,app::get('b2c')->_('邮箱已经存在'));
        }
        // if($member['contact']['phone']['mobile'] && !preg_match('/^1[3458][0-9]{9}$/',$member['contact']['phone']['mobile'])){
        //     return $this->apiData(false,null,400,app::get('b2c')->_('手机输入格式不正确'));
        // }
        $transaction = $db->beginTransaction();
        $sql = 'update ' . DB_PREFIX . 'b2c_members set sex="'.$params['gender'].'",mobile="'.$params['mobile'].'",email="'.$params['email'].'" where member_id='.$member_id;
        $ret = $db->exec($sql);
        if($ret){
            $sql2 = 'update ' . DB_PREFIX . 'business_storemanger set store_idcardname="'.$params['name'].'" where account_id='.$member_id;
            $ret2 = $db->exec($sql2);
            if(!$ret2){
                return $this->apiData(false,null,400,app::get('b2c')->_('修改失败'));
                $db->rollback();
            }
            $db->commit($transaction);
            return $this->apiData(true,array('member_id',$member_id),200,app::get('b2c')->_('保存成功'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('修改失败,请检查是否登录'));
        }
    }

    public function accountinfo($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $login_name = app::get('pam') -> model('account') -> get_operactor_name($member_id);
        $member = $membermdl = app::get('b2c')->model('members')->getList("advance,advance_freeze,member_pic",array('member_id'=>$member_id));
        $storemanger = app::get('business')->model('storemanger')->dump(array('account_id'=>$member_id));
        if(!empty($storemanger)){
            $storegrade = app::get('business')->model('storegrade')->dump(array('grade_id'=>$storemanger['store_grade']),'grade_name');
            $result['grade_name'] = $storemanger['approved']=='1'?$storegrade['grade_name']:app::get('b2c')->_('审核中');
        }else{
            $result['grade_name'] = app::get('b2c')->_('普通会员');
        }
        if(!empty($member[0]['member_pic'])){
            $img = openapi_utils_image::getimgbyid($member[0]['member_pic']);
            $result['member_pic'] = $img['url'];
        }
        $result['login_name'] = $login_name;
        $result['advance'] = $member[0]['advance'];
        $result['advance_freeze'] = $member[0]['advance_freeze'];
        return $this->apiData(true,$result,200);
    }

    
    public function fav($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $sto= kernel::single("business_memberstore",$member_id);
        $sto->process($member_id);
        $st = $sto->storeinfo;
        $store = array(
            'store_id' => $st['store_id'],
            'parent_id' => $st['parent_id'],
            'store_name' =>$st['store_name'],
            );
        $object_type = $params['obj_type'];
        $nGid = $params['gid'];
        $act_type = $params['act_type'];
        $count = app::get('b2c')->model('member_goods')->count(array('member_id'=>$member_id),'fav');
        if($act_type == 'del'){
            if (!kernel::single('b2c_member_fav')->del_fav($member_id,$object_type,$nGid)){
                return $this->apiData(false,array('fav_num'=>$count),400,app::get('b2c')->_('删除失败'));
            }else{
                return $this->apiData(true,array('fav_num'=>--$count),200,app::get('b2c')->_('删除成功'));
            }
        }else{
            if (!app::get('b2c')->model('member_goods')->add_fav($member_id,$object_type,$nGid,$store)){
                return $this->apiData(false,array('fav_num'=>$count),400,app::get('b2c')->_('收藏失败'));
            }else{
                return $this->apiData(true,array('fav_num'=>++$count),200,app::get('b2c')->_('收藏成功'));
            }
        }

    }

    
    public function favlist($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $member = $this->get_current_member();
        $site_member_lv_id = $member['member_lv'];
        $result = app::get('b2c')->model('member_goods')->get_member_fav($member_id);
        $good_ids = explode(",", substr($result, 1));
        $goods = app::get('b2c')->model('goods')->getList("goods_id,bn,name,price,mktprice,image_default_id",array('goods_id|in'=>$good_ids));
        $list2dump = kernel::single("b2c_goods_list2dump");
        foreach ($goods as $key => &$good) {
            $aGoods = $list2dump->get_goods($good,$site_member_lv_id);
            $good['price'] = number_format($aGoods['current_price']);
            $good['mktprice'] = number_format(round($aGoods['mktprice']),2,".","");
            $good['default_image'] = openapi_utils_image::get_img_url($good['image_default_id']);
        }
        return $this->apiData(true,array('favlist'=>$goods),200);
    }

    
    public function my_msg($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $type = $params['msg_type'];
        $nPage = empty($params['npage'])?1:$params['npage'];
        $pagesize = empty($params['pagesize'])?10:$params['pagesize'];
        $oMsg = kernel::single('b2c_message_msg');
        $search_content = $params['search_content'];
        //全部
        if(!$type){
            $row = $oMsg->getList('comment_id,for_comment_id,author,time,reply_name,to_uname,title,comment',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','title|has'=>$search_content));
            $aData['data'] = $row;
            $aData['total'] = count($row);
            $count = count($row);
            $aPage = $this->get_start($nPage,$pagesize,$count);
            $params['data'] = $oMsg->getList('comment_id,for_comment_id,author,author_id,time,reply_name,to_uname,title,comment,mem_read_status',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' =>'true','title|has'=>$search_content),$aPage['start'],$pagesize,"mem_read_status asc,time desc");

            $params['page'] = $aPage['maxPage'];
            $this->pagedata['message'] = $params['data'];
            $this->pagedata['total_msg'] = $aData['total'];

            $this->pagedata['pager'] = array(
                    'current'=>$nPage,
                    'total'=>$params['page'],
                    );
        
        }else if($type == 1){
            //未读
            $row = $oMsg->getList('comment_id,for_comment_id,author,time,reply_name,to_uname,title,comment',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'false','title|has'=>$search_content));
            $aData['data'] = $row;
            #print_r($row);
            $aData['total'] = count($row);
            $count = count($row);
            $aPage = $this->get_start($nPage,$pagesize,$count);
            $params['data'] = $oMsg->getList('comment_id,for_comment_id,author,author_id,time,reply_name,to_uname,title,comment,mem_read_status',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' =>'true','mem_read_status' => 'false','title|has'=>$search_content),$aPage['start'],$pagesize);

            $params['page'] = $aPage['maxPage'];
            $this->pagedata['message'] = $params['data'];
            $this->pagedata['total_msg'] = $aData['total'];

            $this->pagedata['pager'] = array(
                    'current'=>$nPage,
                    'total'=>$params['page'],
                    );
        
        }else if($type == 2){
            //已读
            $row = $oMsg->getList('comment_id',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'true','title|has'=>$search_content));
            $aData['data'] = $row;
            #print_r($row);
            $aData['total'] = count($row);
            $count = count($row);
            $aPage = $this->get_start($nPage,$count);
            $params['data'] = $oMsg->getList('comment_id,for_comment_id,author,author_id,time,reply_name,to_uname,title,comment,mem_read_status',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' =>'true','mem_read_status' => 'true','title|has'=>$search_content),$aPage['start'],$pagesize);

            $params['page'] = $aPage['maxPage'];
            $this->pagedata['message'] = $params['data'];
            $this->pagedata['total_msg'] = $aData['total'];

            $this->pagedata['pager'] = array(
                    'current'=>$nPage,
                    'total'=>$params['page'],
                    );
        
        }

        //站内信条数显示
        $all = $oMsg->getList('*',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true'));
        $all = count($all);

        $no_read = $oMsg->getList('*',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'false'));
        $no_read = count($no_read);
        
        $had_read = $oMsg->getList('*',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'true'));
        $had_read = count($had_read);

        $this->pagedata['type'] = $type;
        $this->pagedata['all'] = $all;
        $this->pagedata['no_read'] = $no_read;
        $this->pagedata['had_read'] = $had_read;

        return $this->apiData(true,$this->pagedata,200);
    }

    
    public function mem_read($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $nMsgId = $params['comment_id'];
        $objMsg = kernel::single('b2c_message_msg');
        $aMsg = $objMsg->getList('*',array('comment_id' => $nMsgId,'for_comment_id' => 'all','to_id'=>$member_id));
        if($aMsg[0]&&($aMsg[0]['author_id']!=$member_id&&$aMsg[0]['to_id']!=$member_id)){
            return $this->apiData(false,null,400,app::get('b2c')->_('对不起，您没有权限查看这条信息！'));
        }
        $objMsg->setReaded($nMsgId);
        //未读数量
        $oMsg = kernel::single('b2c_message_msg');
        $no_read = $oMsg->getList('comment_id',array('to_id' => $member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'false'));
        $result['no_read'] = count($no_read);
        return $this->apiData(true,$result,200);
    }

    
    public function send_msg($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $oMsg = kernel::single('b2c_message_msg');
        $allowList = $oMsg->allowSend($member_id);
        $params['to_name'] = $params['to_id']=='1'?$params['to_name']='admin':$params['to_name'];
        if(!in_array($params['to_name'], $allowList)){
            return $this->apiData(false,null,400,app::get('b2c')->_("只能给总部、直属上级和下级发送站内信"));
        }
        $obj_member = app::get('b2c')->model('members');
        $members = app::get('pam')->model('account')->getRow('login_name',array('account_id'=>$member_id));
        if(empty($params['to_id'])){
            $params['to_id'] = $obj_member->get_id_by_uname($params['to_name']);
        }
        $aData = array(
                'author_id' => $member_id,
                'author' => $members['login_name'],
                'object_type' => 'msg',
                'to_id' =>  $params['to_id'],
                'to_uname' => $params['to_name'],
                'title' =>$params['title'],
                'comment' => $params['content'],
                'time' => time(),
                'ip'=>'openapi',
                'has_sent'=>'true',
                    );
        $re = $oMsg->save($aData);
        
        if($re){
            return $this->apiData(true,null,200,app::get('b2c')->_('发送成功'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('发送失败'));
        }
    }

    
    public function del_inbox_msg($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $objMsg = kernel::single('b2c_message_msg');
        $deleteArr = explode(",", $params['delete']);
        if($objMsg->check_msg($deleteArr,$member_id))
        {
            if($objMsg->delete_msg($deleteArr,'inbox'))
                return $this->apiData(true,null,200,app::get('b2c')->_('删除成功！'));
            else return $this->apiData(false,null,400,app::get('b2c')->_('删除失败！'));
        }
        else
        {
            return $this->apiData(false,null,400,app::get('b2c')->_('删除失败: 参数提交错误！！'));
        }
    }

    
    public function suroundstore($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $npage = empty($params['npage'])?1:$params['npage'];
        $pagesize = 10;
        $scontent = trim($params['scontent']);
        if(!empty($scontent)){
            $filter['store_name|has'] = $scontent;
        }
        $filter['area|has'] = $params['area'];
        $mdl_member = app::get('b2c')->model('members');
        $business = app::get('business')->model('storemanger')->getList('store_name,store_grade,area,addr,account_id',$filter,($npage-1)*$pagesize,$pagesize);
        foreach ($business as $key => &$bus) {
            $area = explode(":", $bus['area']);
            $bus['area'] = str_replace("/", "", $area[1]);
            $member = $mdl_member->getRow('mobile,email',array('member_id'=>$bus['account_id']));
            $bus['tel'] = empty($member['mobile'])?"":$member['mobile'];
            $bus['email'] = empty($member['email'])?"":$member['email'];
        }
        return $this->apiData(true,$business,200);
    }

    
    public function ConponsList($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $storeinfo = app::get('business')->model('storemanger')->getRow("*",array('account_id'=>$member_id));
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = 10;
        //已领取的优惠券
        $mdl_member_coupons = app::get('b2c')->model('member_coupon');
        $my_coupons = $mdl_member_coupons->getList("cpns_id",array('member_id'=>$member_id,'disabled'=>'false'));
        $my_cpns_ids = array();
        foreach ($my_coupons as $key => $value) {
            $my_cpns_ids[] = $value['cpns_id'];
        }
        $sql = "SELECT r.description,r.from_time,r.to_time,c.cpns_id,c.cpns_name,r.action_solution,r.`status`,r.store_grade_ids from " . DB_PREFIX . "b2c_coupons c LEFT JOIN " . DB_PREFIX . "b2c_sales_rule_order r on c.rule_id=r.rule_id where r.to_time>unix_timestamp() and c.cpns_status='1' and c.cpns_id not in ('".implode("','", $my_cpns_ids)."')";
        $list = app::get('b2c')->model('coupons')->db->select($sql);
        if(empty($list)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        $conpons = array();
        foreach ($list as $k => $v) {
            $grade_ids = explode(',', $rule['store_grade_ids']);
            if(!in_array($storeinfo['store_grade'], $grade_ids)){
                continue;//不符合层级的不显示
            }
            $rule = array();
            $rule['description'] = $v['description'];
            $rule['from_time'] = date('Y-m-d H:i:s',$v['from_time']);
            $rule['to_time'] = date('Y-m-d H:i:s',$v['to_time']);
            $rule['cpns_id'] = $v['cpns_id'];
            $rule['name'] = $v['cpns_name'];
            $tmp = current(unserialize($v['action_solution']));
            $rule['discount_amount'] = $tmp['total_amount'];
            $rule['status'] = 0;//状态为0 可领取 已领取的已经被过滤
            $conpons[] = $rule;
        }
        return $this->apiData(true,$conpons,200);
    }

    
    public function getConpons($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $oMember = kernel::single('b2c_api_site_member',$member_id);
        $res = $oMember->getCoupons($params['cpns_id'],$err_msg);
        if($res){
            return $this->apiData(true,array('cpns_id'=>$params['cpns_id']),200,app::get('b2c')->_($err_msg));
        }
        return $this->apiData(false,array('cpns_id'=>$params['cpns_id']),400,app::get('b2c')->_($err_msg));
    }

    
    public function myCoupons($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $storeinfo = app::get('business')->model('storemanger')->getRow('*',array('account_id'=>$member_id));
        
        $npage = $params['npage']?$params['npage']:1;
        $pagelimit=10;
        $mobj_coupon = app::get('b2c')->model('member_coupon');
        $filter = array('member_id'=>$member_id);
        $filter['disabled'] = 'false';
        $filter['memc_isvalid'] = 'true';
        $aData=$mobj_coupon->_get_list('*',$filter,$pagelimit*($npage-1),$pagelimit);
        if ($aData) {
            $result = array();
            foreach ($aData as $k => $item) {
                $tmp = array();
                $tmp['status'] = 1;
                if ($item['coupons_info']['cpns_status']==1) {
                    $grade_ids = explode(',',$item['time']['store_grade_ids']);
                    if (in_array($storeinfo['store_grade'],(array)$grade_ids)) {
                        $curTime = time();
                        if ($curTime>=$item['time']['from_time'] && $curTime<$item['time']['to_time']) {
                            if ($item['memc_used_times']<app::get('b2c')->getConf('coupon.mc.use_times')){
                                if ($item['coupons_info']['cpns_status']){
                                    if($item['memc_isactive']=='false'){
                                       $aData[$k]['memc_status'] = app::get('b2c')->_('未激活');
                                    }else{
                                        $aData[$k]['memc_status'] = app::get('b2c')->_('可使用');
                                        $tmp['status'] = 0;
                                    }
                                }else{
                                    $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券已作废');
                                }
                            }else{
                                $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券次数已用完');
                            }
                        }else{
                            $aData[$k]['memc_status'] = app::get('b2c')->_('还未开始或已过期');
                        }
                    }else{
                        $aData[$k]['memc_status'] = app::get('b2c')->_('本级别不准使用');
                    }
                }else{
                    $aData[$k]['memc_status'] = app::get('b2c')->_('此种优惠券已取消');
                }
                $tmp['memc_status'] = $aData[$k]['memc_status'];
                $tmp['memc_code'] = $aData[$k]['memc_code'];
                $tmp['name'] = $aData[$k]['coupons_info']['cpns_name'];
                $tmp['cpns_id'] = $aData[$k]['coupons_info']['cpns_id'];
                $tmp['description'] = $aData[$k]['time']['description'];
                $tmp['from_time'] = date('Y-m-d H:i:s',$aData[$k]['time']['from_time']);
                $tmp['to_time'] = date('Y-m-d H:i:s',$aData[$k]['time']['to_time']);
                $tmp['discount_amount'] = $aData[$k]['time']['discount_amount'];
                if($params['ispay']!=1 || $tmp['status']==0){
                    $result[] = $tmp;
                }
            }
            return $this->apiData(true,$result,200);
        }
        return $this->apiData(false,null,400,app::get('b2c')->_('没有可用的优惠券'));
    }
}